__author__ = 'wwj'
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from celery.utils.log import get_task_logger
import pymongo
import sys
import os
sys.path.append("/Users/wwj/PycharmProjects")
from dispatch.main import app
logger = get_task_logger(__name__)
import youtube_dl
OUTSTANAING = 0 #未处理 当添加一个新url时，其url状态。
PROCESSING = 1 #待处理 当url从队列中取出准备下载是，其url状态。
COMPLETE = 2 #已处理 当下载结束后，其url状态。
ERROR = 3 #处理失败 当下载失败时，其url状态。

class basetask(app.Task):
    def on_success(self, retval, task_id, args, kwargs):   # 任务成功执行
        client.xvideo.update(
            {'url': kwargs.get("url")},
            {'$set': {'status': self.COMPLETE, 'wait_time': datetime.datetime.now()}}
        )
        logger.info('task id:{} , arg:{} , successful !'.format(task_id,args))

    def on_failure(self, exc, task_id, args, kwargs, einfo):  #任务失败执行
        client.xvideo.update(
            {'url': kwargs.get("url")},
            {'$set': {'status': self.ERROR, 'wait_time': datetime.datetime.now()}}
        )
        logger.info('task id:{} , arg:{} , failed ! erros : {}' .format(task_id,args,exc))

    def on_retry(self, exc, task_id, args, kwargs, einfo):    #任务重试执行
        logger.info('task id:{} , arg:{} , retry !  einfo: {}'.format(task_id, args, exc))


import hashlib
@app.task(bind=True,base=basetask, default_retry_delay=300, max_retries=1)
def down(self,url):
    url = "https://www.youtube.com/watch?v=BaW_jenozKc"
    # ydl_opts = {
    #     # 'format': 'bestaudio/best',
    #     # 'postprocessors': [{
    #     #     'key': 'FFmpegExtractAudio',
    #     #     'preferredcodec': 'mp3',
    #     #     'preferredquality': '192',
    #     # }],
    #     'outtmpl': '/mnt/{}'.fatmat(hashlib.md5(url).hexdigest())
    # }
    ydl_opts["outtmpl"] = '/mnt/{}'.format(hashlib.md5(url.encode("utf8")).hexdigest())
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

# @app.on_after_configure.connect
@app.on_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    import ipdb;ipdb.set_trace()
    for x in client.xvideo.video.find({"$ne":{"status":""}},{"url":1}):
        sender.add_periodic_task(1.0, down.s(x["url"]), name='xvideo',queue='xvideo')



